<template>
  <w-modal
    ref="WModal"
    title="二维码识别"
    :ok-type="identifyData? 'danger' : 'primary'"
    :ok-text="identifyData ? '清 除' : '确 定'"
    @ok="imageInentifyBtnClick"
  >
    <image-up ref="WImageUp" />
    <div v-if="identifyData && identifyData.text.length">
      <br>
      <a-row>
        <a-col span="2">
          类型
        </a-col>
        <a-col span="22">
          {{ identifyData.type }}
        </a-col>
      </a-row>
      <br>
      <a-row>
        <a-col span="2">
          数据
        </a-col>
        <a-col span="22">
          <p v-for="(v, k) in identifyData.text" :key="k">
            {{ v }}
          </p>
        </a-col>
      </a-row>
    </div>
  </w-modal>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import { Api } from '@/config/api'
import ImageUp from '@/components/global/imageUp/server'
import WModal, { ModalComType } from '@/components/global/modal'

@Component({
  name: 'ComWebToolBarCodeIdentify',
  components: {
    ImageUp,
    WModal
  }
})
export default class ComWebToolBarCodeIdentify extends Vue {
  // 识别出的文字
  identifyData = null;

  // 图片识别按钮点击
  imageInentifyBtnClick () {
    if (this.identifyData) {
      this.identifyData = null;
      (this.$refs.WImageUp as any).clear()
      return
    }
    (this.$refs.WModal as ModalComType).showLoading();
    (this.$refs.WImageUp as any)
      .upImage()
      .then((data: any) => {
        this.$wAxios
          .$post(Api.baidu.qrcodeIdentify, {
            localPath: data.filepath
          })
          .then((data) => {
            if (data.codes_result && data.codes_result.length > 0) {
              const [codeData] = data.codes_result
              this.identifyData = codeData
            } else {
              this.$message.error('没有识别出')
            }
          })
          .catch(() => {
            this.identifyData = null
          })
          .finally(() => {
            (this.$refs.WModal as ModalComType).hideLoading()
          })
      })
      .catch((err: any) => {
        this.$message.error(err.msg)
      })
      .finally(() => {
        (this.$refs.WModal as ModalComType).hideLoading()
      })
  }

  /**
   * 显示弹窗
   */
  show () {
    (this.$refs.WModal as ModalComType).show()
  }

  /**
   * 显示状态改变的时候调用
   */
  visibleChange (state: any) {
    if (state) {
      (this.$refs.WImageUp as any).clear()
    }
  }
}
</script>

<style scoped></style>
